package com.one.login.intercept;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.one.login.common.RedisUtil;
import com.one.login.pojo.vo.LoginTicket;
import com.one.login.pojo.vo.User;
import com.one.login.service.UserService;
import com.one.login.util.Util;

//登录拦截
public class LoginIntercept implements HandlerInterceptor {

	private RedisUtil redisUtil;

	private UserService userService;

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		// 获取cookie
		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("userId");
		// 判断是否登录
		// 已登录
		if (userId != null) {
			System.out.println("------111------");
			// 重定向到原页面
			String url = request.getParameter("url");
			response.addCookie(new Cookie("JSESSIONID", session.getId()));
			String st = Util.UUID();
			// st存入redis里
			// ******************
			LoginTicket loginTicket = new LoginTicket();
			// 获取用户
			User user = userService.selectOneById(userId);
			// 设置用户
			loginTicket.setUser(user);
			// 
			redisUtil.setObject(LoginTicket.class, loginTicket, "one-login", st);
			// ******************
			response.sendRedirect(url + "?st=" + st);
			return true;
		}
		// 未登录
		System.out.println("------222------");
		response.sendRedirect("/intent/login.html");
		return false;
	}

}
